package org.itboys.pay.weixin;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.itboys.commons.CommonConstants;
import org.itboys.pay.alipay.AlipayWapResult;
import org.itboys.pay.constant.PayConstants;
import org.itboys.pay.tools.XMLUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 微信支付回调签名校验
 * 
 * @author ChenJunhui
 * 
 */
public class WXPayService {
	private static Logger logger = LoggerFactory.getLogger(WXPayService.class);
	/**
	 * 验证异步回调并返回结果
	 * @param key  微信支付key
	 * @return AlipayWapResult
	 */
	@SuppressWarnings("unchecked")
	public static AlipayWapResult notifyResult(HttpServletRequest request,
			String key) throws Exception {
		AlipayWapResult result = new AlipayWapResult();
		Map<String, String> params = XMLUtil
				.doXMLParse(inputStream2String(request.getInputStream())); // DCHttpUtils.getParams(request);
		for (Map.Entry<String, String> entry : params.entrySet()) {
			logger.info("Key = " + entry.getKey() + ", Value = " + entry.getValue());
		}
//		result.setParams(params);
//		result.setTrade_status(params.get(PayConstants.WeixinPay.RETURN_CODE));
//		result.setPrice(new BigDecimal(params.get(PayConstants.WeixinPay.TOTAL_FEE))
//				.divide(new BigDecimal(100)));
		result.setOut_trade_no(params.get(PayConstants.OUT_TRADE_NO));
		result.setTrade_no(params.get(PayConstants.WeixinPay.TRANSACTION_ID));

		result.setTrade_status(params.get(PayConstants.WeixinPay.RETURN_CODE));
		result.setPrice(new BigDecimal(params.get(PayConstants.WeixinPay.TOTAL_FEE))
				.divide(new BigDecimal(100)));
		if (result.getTrade_status().equals(CommonConstants.SUCCESS)) {
			if (params.get(PayConstants.WeixinPay.RESULT_CODE).equals(CommonConstants.SUCCESS)) {
				if (WXPayNotify.verifyNotify(params, key)) {// 验证成功
					result.setVerify_result(true);
					result.setOut_trade_no(params.get(PayConstants.OUT_TRADE_NO));
					result.setTrade_no(params.get(PayConstants.WeixinPay.TRANSACTION_ID));
				} else {
					result.setVerify_result(false);
				}
			} else {
				result.setVerify_result(false);
			}
		} else {
			result.setVerify_result(false);
		}
		return result;
	}

	public static AlipayWapResult checkIsSuccess(AlipayWapResult result, String key){
		if (result.getTrade_status().equals(CommonConstants.SUCCESS)) {
			if (result.getParams().get(PayConstants.WeixinPay.RESULT_CODE).equals(CommonConstants.SUCCESS)) {
				if (WXPayNotify.verifyNotify(result.getParams(), key)) {// 验证成功
					result.setVerify_result(true);
				} else {
					result.setVerify_result(false);
				}
			} else {
				result.setVerify_result(false);
			}
		} else {
			result.setVerify_result(false);
		}
		return result;
	}

	private static String inputStream2String(InputStream in) throws IOException {
		StringBuffer out = new StringBuffer();
		byte[] b = new byte[4096];
		for (int n; (n = in.read(b)) != -1;) {
			out.append(new String(b, 0, n));
		}
		return out.toString();
	}
	
	/**
	 * 查询微信订单支付状态
	 * @param outTradeNo
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public static String orderQuery(String outTradeNo, String appid, String mchId, String key) throws Exception{
		WeixinOrderQuery orderquery = new WeixinOrderQuery(appid, mchId, StringUtils.EMPTY, outTradeNo, key);
		String param = orderquery.getXmlParam();
		String result = WeixinPayUtils.execute(param, WeixinOrderQuery.URL);
		logger.info("*************orderQuery result***************" + result);
		if(StringUtils.isNotBlank(result)){
			Map<String, Object> map = XMLUtil.doXMLParse(result);
			String returnCode = (String)map.get(PayConstants.WeixinPay.RETURN_CODE);
			String resultCode = (String)map.get(PayConstants.WeixinPay.RESULT_CODE);
			if(returnCode.toLowerCase().equals(CommonConstants.SUCCESS) && resultCode.toLowerCase().equals(CommonConstants.SUCCESS)){
				String tradeState = (String)map.get("trade_state");
				/**
				 * SUCCESS—支付成功
					REFUND—转入退款
					NOTPAY—未支付
					CLOSED—已关闭
					REVOKED—已撤销（刷卡支付）
					USERPAYING--用户支付中
					PAYERROR--支付失败(其他原因，如银行返回失败)
				 */
				return tradeState;
			}else {//查询失败
				String returnMsg = (String)map.get(PayConstants.WeixinPay.RETURN_MSG);
				String errCode = (String)map.get(PayConstants.WeixinPay.ERR_CODE);
				String errCodeDes = (String)map.get(PayConstants.WeixinPay.ERR_CODE_DES);
				return CommonConstants.FAIL;
			}
		}
		return CommonConstants.FAIL;
	}
	
}
